package com.chen.nio.demo;

import io.netty.buffer.ByteBuf;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NioClient {

    public static void main(String[] args) throws Exception {
        Selector selector = Selector.open();

        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 8899));
        socketChannel.register(selector, SelectionKey.OP_CONNECT);

        while (true) {
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isConnectable()) {
                    SocketChannel client = (SocketChannel) selectionKey.channel();
                    if (client.isConnectionPending()) {
                        client.finishConnect();
                        //通知服务器端连接成功
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        buffer.put((LocalDateTime.now() + "连接成功").getBytes());
                        buffer.flip();
                        client.write(buffer);

                        ExecutorService executor = Executors.newSingleThreadExecutor();
                        executor.submit(() -> {
                            while(true) {
                                BufferedReader br = null;
                                try {
                                    buffer.clear();
                                    br = new BufferedReader(new InputStreamReader(System.in));
                                    String msg = br.readLine();
                                    buffer.put(msg.getBytes());
                                    buffer.flip();
                                    client.write(buffer);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                        });

                        client.register(selector, SelectionKey.OP_READ);
                    }
                } else if (selectionKey.isReadable()) {
                    SocketChannel client = (SocketChannel) selectionKey.channel();
                    ByteBuffer buf = ByteBuffer.allocate(1024);
                    while (true) {
                        buf.clear();
                        int len = client.read(buf);
                        if (len <= 0) {
                            break;
                        }
                        String message = new String(buf.array(), 0, len);
                        System.out.println(message);
                    }
                }
                iterator.remove();
            }
        }


    }
}
